/**
 * Created with IntelliJ IDEA.
 * Description:寻找峰值
 * User: bjc
 * Date: 2025-11-16
 * Time: 16:38
 */
public class Test06_findPeakElement {
    public int findPeakElement(int[] arr) {
        if (arr.length == 1)
            return 0;
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;

            // 确保不会越界后再访问 arr[mid + 1]
            if (mid < arr.length - 1 && arr[mid] < arr[mid + 1]) {
                // 上升趋势，峰值在右侧
                left = mid + 1;
            } else if (mid > 0 && arr[mid] < arr[mid - 1]) {
                // 下降趋势，峰值在左侧
                right = mid - 1;
            } else {
                // 当前就是峰值点
                return mid;
            }
        }
        return -1;
    }
    //利用模版
    public int findPeakElement1(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            //下降趋势，峰值在左边肯定存在
            if (nums[mid] > nums[mid + 1])
                right = mid;
                //上升趋势，峰值在右边肯定存在
            else if (nums[mid] < nums[mid + 1])
                left = mid + 1;
        }
        return left;
    }
}
